﻿using System;
using System.Data;
using Util.Database;

namespace ConfigureNZBLoader.EditControls
{
    public partial class Feed : BaseEditControl
    {
        public Feed()
        {
            InitializeComponent();
        }

        private long _ID;
        public long ID
        {
            get { return _ID; }
        }

        private string _FeedName;
        public string FeedName
        {
            get { return _FeedName; }
        }

        private string _Address;
        public string Address
        {
            get { return _Address; }
        }

        public void Open(long ID)
        {
            //Open existing entry
            _ID = ID;
            using (IDbCommand cmd = DB.CreateCommand())
            {
                cmd.CommandText = "select * from feed where id=?";
                IDataParameter par = cmd.CreateParameter();
                par.Value = ID;
                cmd.Parameters.Add(par);

                using (IDataReader dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        _FeedName = dr["NAME"].ToString();
                        _Address = dr["ADDRESS"].ToString();
                    }
                    else
                    {
                        throw new ArgumentException("Invalid ID", "ID");
                    }
                }
            }

            txtName.Text = _FeedName;
            txtAddress.Text = _Address;
        }


        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!txtAddress.Text.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase))
            {
                if (System.Windows.Forms.DialogResult.Yes != System.Windows.Forms.MessageBox.Show("The address doesn't start with \"http://\". Do you want to continue?", "Are you sure?", System.Windows.Forms.MessageBoxButtons.YesNo))
                {
                    return;
                }
            }

            _FeedName = txtName.Text;
            _Address = txtAddress.Text;

            //Update database
            using (IDbCommand cmd = DB.CreateCommand())
            {
                cmd.CommandText = "update feed set name=?, address=? where id=?";
                IDataParameter par = cmd.CreateParameter();
                par.Value = FeedName;
                cmd.Parameters.Add(par);
                par = cmd.CreateParameter();
                par.Value = Address;
                cmd.Parameters.Add(par);
                par = cmd.CreateParameter();
                par.Value = ID;
                cmd.Parameters.Add(par);

                cmd.ExecuteNonQuery();
            }


            ItemChangedNotification(FeedName);
        }
    }
}
